Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Nested Loops

Nested loops in Java

In Java, you can nest any type of loop within another loop. The types of loops in Java are for, while, and do-while. Here’s a brief explanation of each type of nested loop

Nested For Loops

A nested for loop is a loop inside another for loop. The inner loop executes its iterations for each iteration of the outer loop.
Nested For Loops
for(int i = 0; i < 5; i++) { // Outer for loop for(int j = 0; j < 5; j++) { // Inner for loop System.out.print("* "); } System.out.println(); }

Nested While Loops

A nested while loop is a while loop inside another while loop. The inner loop executes its iterations for each iteration of the outer loop.
Nested While Loops
int i = 0; while(i < 5) { // Outer while loop int j = 0; while(j < 5) { // Inner while loop System.out.print("* "); j++; } System.out.println(); i++; }

Nested Do-While Loops

A nested do-while loop is a do-while loop inside another do-while loop. The inner loop executes its iterations for each iteration of the outer loop.
Nested Do-While Loops
int i = 0; do { // Outer do-while loop int j = 0; do { // Inner do-while loop System.out.print("* "); j++; } while(j < 5); System.out.println(); i++; } while(i < 5);

Mixed Nested Loops

You can also mix different types of loops. For example, you can have a for loop inside a while loop, or a do-while loop inside a for loop, and so on. Lets see the mixed nested loops in next one. Remember, when using nested loops, each type of loop can be controlled with its own unique condition, providing flexibility in how your Java program executes loops.

  📌TAGS

★Nested loops ★ for ★while ★do-while ★ java

Tutorials